<template>
  <div>
    <!-- 顶部 -->
    <div>
      <van-nav-bar fixed>
        <template #left>
          <img class="logo" src="@/assets/img/logo.jpg" alt="" />
          <!-- <span class="text">条</span> -->
        </template>
        <template #right>
          <van-icon name="search" size="0.48rem" color="white" @click="onJumpSearch"/>
        </template>
      </van-nav-bar>
    </div>
    <!-- 中部导航 -->
    <!-- 频道部分 -->
    <div class="mian">
      <van-tabs v-model="channelId" animated sticky offset-top="1.226667rem"  :before-change="tabsBeforeChangeFn" @change="tabsChangeFn">
        <van-tab
          v-for="item in userChannelList"
          :key="item.id"
          :title="item.name"
          :name="item.id"

        >
          <ArticleList :channelId="channelId" />
        </van-tab>
      </van-tabs>
      <van-icon
        name="bars"
        size="0.5rem"
        class="moreChannels"
        @click="showPopup"
      />
    </div>
    <!-- 频道管理弹出层 -->
    <van-popup class="home_popup" v-model="show" position="left" duration="0.2">
      <ChannelEdit
        @close="onClosePopup"
        :userList="userChannelList"
        :unCheckList="unCheckChannelList"
        @addChannelEvent="onaddChannel"
        @deleteChannelEvent="onRemoveChannel"
        v-model="channelId"
        ref="eidtRef"
      ></ChannelEdit>
    </van-popup>
  </div>
</template>

<script>
// 引入api
import { getUserchannelsAPI, getAllchannelsAPI, updateChannelAPI, removeThenChannelAPI } from '@/api'
// 引入列表组件
import ArticleList from '@/views/Home/components/ArticleList.vue'
// 引入频道编辑组件
import ChannelEdit from './ChannelEdit'

export default {
  data () {
    return {
      channelId: 0, // tab导航-激活频道ID（默认频道id为零）
      userChannelList: [], // 用户选择频道数据
      show: false, // 弹出层显示/隐藏
      allChannelList: [], // 所有频道数据
      nameToTop: {}// “频道名称”和“滚动条位置”之间的对应关系，格式 { '推荐ID': 211, 'htmlID': 30}
    }
  },
  async created () {
    // 用户频道数据
    const res = await getUserchannelsAPI()
    this.userChannelList = res.data.data.channels

    // 所有频道
    const res2 = await getAllchannelsAPI()
    this.allChannelList = res2.data.data.channels
  },
  components: {
    ArticleList,
    ChannelEdit
  },
  methods: {
    // 弹出层显示
    showPopup () {
      this.show = true
    },
    // 添加频道
    async  onaddChannel (channelObj) {
      // 添加到用户已选的里面
      this.userChannelList.push(channelObj)
      // 把最新的数组。发送给后台
      // const res3 = await updateChannelAPI({ channels: this.userChannelList })
      // console.log(res3)
      const newArr = this.userChannelList.filter(obj => obj.id !== 0)// 去除推荐
      const theNewArr = newArr.map((obj, index) => {
        const newObj = { ...obj }// (浅拷贝)
        delete newObj.name
        newObj.seq = index
        return newObj
      })
      const resup = await updateChannelAPI({ channels: theNewArr })
      console.log(resup)
    },
    // 删除频道
    async onRemoveChannel (channelObj) {
      const index = this.userChannelList.findIndex(obj => obj.id === channelObj.id)
      this.userChannelList.splice(index, 1)
      const resdel = await removeThenChannelAPI({ channelId: channelObj.id })
      console.log(resdel)
    },
    // 关闭弹出层内部编辑状态回归false
    onClosePopup () {
      this.show = false
      this.$refs.eidtRef.isEdit = false
    },
    // 跳转搜索页面
    onJumpSearch () {
      this.$router.push('/search')
    },
    // 频道切换之前触发
    tabsBeforeChangeFn () {
      this.nameToTop[this.channelId] = window.scrollY // 先保存要被切走频道的滚动距离
      // return true让tabs切换
      return true
    },
    // 频道切换后
    tabsChangeFn (channelId) {
      this.$nextTick(() => {
        window.scrollTo(0, this.nameToTop[channelId] || 0)
      })
    }
  },
  computed: {
    unCheckChannelList () {
      // 把所有频道与用户选择频道进行对比，返回未选择的
      // 人读代码 。。。。
      // const newAll = this.allChannelList.filter(bigObj => {
      //   const index = this.userChannelList.findIndex(smallObj => {
      //     return smallObj.id === bigObj.id
      //   })
      //   // 如果相同去除
      //   if (index > -1) {
      //     return false
      //   } else {
      //     return true
      //   }
      // })
      // return newAll

      // 电脑读代码。。。
      return this.allChannelList.filter(
        (bigObj) =>
          this.userChannelList.findIndex(
            (smallObj) => smallObj.id === bigObj.id
          ) === -1
      )
    }
  },
  // 路由离开 - 触发(保存滚动位置)
  beforeRouteLeave (to, from, next) {
    from.meta.top = window.scrollY
    next()
  }
}
</script>

<style scoped lang="less">
.logo {
  border-radius: 18px;
  width: 35px;
  height: 35px;
}
.text {
  font-size: 13px;
  color: #fff;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content {
  padding-top: 44px;
}
/deep/.van-tab--active {
  font-weight: bold;
  font-size: 18px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}
// 弹出层铺满
.home_popup {
  width: 100vw;
  height: 100vh;
}
</style>
